﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 进货订单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class IncomingordersService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Incomingorders> _incomingordersRep;
    private readonly SysFileService _sysFileService;
    private readonly ISqlSugarClient _sqlSugarClient;

    public IncomingordersService(SqlSugarRepository<Incomingorders> incomingordersRep, SysFileService sysFileService, ISqlSugarClient sqlSugarClient)
    {
        _incomingordersRep = incomingordersRep;
        _sysFileService = sysFileService;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询进货订单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询进货订单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<IncomingordersOutput>> Page(PageIncomingordersInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _incomingordersRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.IncomingNumber.Contains(input.Keyword) || u.OrdersStatus.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.ContactManaer.Contains(input.Keyword) || u.GoodsName.Contains(input.Keyword) || u.IncomingDesc.Contains(input.Keyword) || u.OrganizationalStructureId.Contains(input.Keyword) || u.StorageDesc.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.IncomingNumber), u => u.IncomingNumber.Contains(input.IncomingNumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OrdersStatus), u => u.OrdersStatus.Contains(input.OrdersStatus.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ContactManaer), u => u.ContactManaer.Contains(input.ContactManaer.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.IncomingDesc), u => u.IncomingDesc.Contains(input.IncomingDesc.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OrganizationalStructureId), u => u.OrganizationalStructureId.Contains(input.OrganizationalStructureId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.StorageDesc), u => u.StorageDesc.Contains(input.StorageDesc.Trim()))
            .WhereIF(input.IncomingDataRange?.Length == 2, u => u.IncomingData >= input.IncomingDataRange[0] && u.IncomingData <= input.IncomingDataRange[1])
            .WhereIF(input.Vendor != null, u => u.Vendor == input.Vendor)
            .WhereIF(input.IncomingDepId != null, u => u.IncomingDepId == input.IncomingDepId)
            .WhereIF(input.IncomingPeopleId != null, u => u.IncomingPeopleId == input.IncomingPeopleId)
            .WhereIF(input.GoodsNum != null, u => u.GoodsNum == input.GoodsNum)
            .WhereIF(input.GoodsPrices != null, u => u.GoodsPrices == input.GoodsPrices)
            .WhereIF(input.MakeSingleId != null, u => u.MakeSingleId == input.MakeSingleId)
            .WhereIF(input.DepId != null, u => u.DepId == input.DepId)
            .WhereIF(input.MakeDataRange?.Length == 2, u => u.MakeData >= input.MakeDataRange[0] && u.MakeData <= input.MakeDataRange[1])
            .WhereIF(input.AuditTimeRange?.Length == 2, u => u.AuditTime >= input.AuditTimeRange[0] && u.AuditTime <= input.AuditTimeRange[1])
            .WhereIF(input.Operator != null, u => u.Operator == input.Operator)
            .LeftJoin<Vendor>((u, vendor) => u.Vendor == vendor.Id)
            .LeftJoin<department>((u, vendor, incomingDep) => u.IncomingDepId == incomingDep.Id)
            .LeftJoin<UserInfo>((u, vendor, incomingDep, incomingPeople) => u.IncomingPeopleId == incomingPeople.Id)
            .LeftJoin<UserInfo>((u, vendor, incomingDep, incomingPeople, makeSingle) => u.MakeSingleId == makeSingle.Id)
            .LeftJoin<department>((u, vendor, incomingDep, incomingPeople, makeSingle, dep) => u.DepId == dep.Id)
            .LeftJoin<UserInfo>((u, vendor, incomingDep, incomingPeople, makeSingle, dep, op) => u.Operator == op.Id)
            .Select((u, vendor, incomingDep, incomingPeople, makeSingle, dep, op) => new IncomingordersOutput
            {
                Id = u.Id,
                IncomingNumber = u.IncomingNumber,
                OrdersStatus = u.OrdersStatus,
                IncomingData = u.IncomingData,
                Vendor = u.Vendor,
                VendorFkDisplayName = $"{vendor.VendorName}",
                Contact = u.Contact,
                ContactManaer = u.ContactManaer,
                IncomingDepId = u.IncomingDepId,
                IncomingDepFkDisplayName = $"{incomingDep.DepartmentName}",
                IncomingPeopleId = u.IncomingPeopleId,
                IncomingPeopleFkDisplayName = $"{incomingPeople.UserName}",
                GoodsNum = u.GoodsNum,
                GoodsPrices = u.GoodsPrices,
                GoodsName = u.GoodsName,
                MakeSingleId = u.MakeSingleId,
                MakeSingleFkDisplayName = $"{makeSingle.UserName}",
                DepId = u.DepId,
                DepFkDisplayName = $"{dep.DepartmentName}",
                IncomingDesc = u.IncomingDesc,
                MakeData = u.MakeData,
                AuditTime = u.AuditTime,
                OrganizationalStructureId = u.OrganizationalStructureId,
                StorageDesc = u.StorageDesc,
                Operator = u.Operator,
                OperatorFkDisplayName = $"{op.UserName}",
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取进货订单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取进货订单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Incomingorders> Detail([FromQuery] QueryByIdIncomingordersInput input)
    {
        return await _incomingordersRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加进货订单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加进货订单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddIncomingordersInput input)
    {
        var entity = input.Adapt<Incomingorders>();
        return await _incomingordersRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新进货订单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新进货订单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateIncomingordersInput input)
    {
        var entity = input.Adapt<Incomingorders>();
        await _incomingordersRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除进货订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除进货订单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteIncomingordersInput input)
    {
        var entity = await _incomingordersRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _incomingordersRep.FakeDeleteAsync(entity);   //假删除
        //await _incomingordersRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除进货订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除进货订单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteIncomingordersInput> input)
    {
        var exp = Expressionable.Create<Incomingorders>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _incomingordersRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _incomingordersRep.FakeDeleteAsync(list);   //假删除
        //return await _incomingordersRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 上传上传附件 ⬆️
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [DisplayName("上传上传附件")]
    [ApiDescriptionSettings(Name = "UploadStorageDesc"), HttpPost]
    public async Task<SysFile> UploadStorageDesc([Required] IFormFile file)
    {
        return await _sysFileService.UploadFile(new UploadFileInput { File = file, SavePath = "upload/Incomingorders/StorageDesc" }); 
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataIncomingordersInput input)
    {
        var vendorData = await _incomingordersRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.Vendor)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var incomingDepIdData = await _incomingordersRep.Context.Queryable<department>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.IncomingDepId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var incomingPeopleIdData = await _incomingordersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.IncomingPeopleId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var makeSingleIdData = await _incomingordersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.MakeSingleId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var depIdData = await _incomingordersRep.Context.Queryable<department>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.DepId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.DepartmentName}"
            }).ToListAsync();
        var operatorData = await _incomingordersRep.Context.Queryable<UserInfo>()
            .InnerJoinIF<Incomingorders>(input.FromPage, (u, r) => u.Id == r.Operator)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "vendor", vendorData },
            { "incomingDepId", incomingDepIdData },
            { "incomingPeopleId", incomingPeopleIdData },
            { "makeSingleId", makeSingleIdData },
            { "depId", depIdData },
            { "operator", operatorData },
        };
    }
    
    /// <summary>
    /// 导出进货订单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出进货订单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageIncomingordersInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportIncomingordersOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "进货订单导出记录");
    }
    
    /// <summary>
    /// 下载进货订单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载进货订单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportIncomingordersOutput>(), "进货订单导入模板", (_, info) =>
        {
            if (nameof(ExportIncomingordersOutput.VendorFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportIncomingordersOutput.IncomingDepFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportIncomingordersOutput.IncomingPeopleFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportIncomingordersOutput.MakeSingleFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportIncomingordersOutput.DepFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<department>().Select(u => $"{u.DepartmentName}").Distinct().ToList();
            if (nameof(ExportIncomingordersOutput.OperatorFkDisplayName) == info.Name) return _incomingordersRep.Context.Queryable<UserInfo>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入进货订单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入进货订单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportIncomingordersInput, Incomingorders>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 供应商
                    var vendorLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorLabelList.Any()) {
                        var vendorLinkMap = _incomingordersRep.Context.Queryable<Vendor>().Where(u => vendorLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Vendor = vendorLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.Vendor == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 进货部门
                    var incomingDepIdLabelList = pageItems.Where(x => x.IncomingDepFkDisplayName != null).Select(x => x.IncomingDepFkDisplayName).Distinct().ToList();
                    if (incomingDepIdLabelList.Any()) {
                        var incomingDepIdLinkMap = _incomingordersRep.Context.Queryable<department>().Where(u => incomingDepIdLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.IncomingDepId = incomingDepIdLinkMap.GetValueOrDefault(e.IncomingDepFkDisplayName ?? "");
                            if (e.IncomingDepId == null) e.Error = "进货部门链接失败";
                        });
                    }
                    // 链接 进货人
                    var incomingPeopleIdLabelList = pageItems.Where(x => x.IncomingPeopleFkDisplayName != null).Select(x => x.IncomingPeopleFkDisplayName).Distinct().ToList();
                    if (incomingPeopleIdLabelList.Any()) {
                        var incomingPeopleIdLinkMap = _incomingordersRep.Context.Queryable<UserInfo>().Where(u => incomingPeopleIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.IncomingPeopleId = incomingPeopleIdLinkMap.GetValueOrDefault(e.IncomingPeopleFkDisplayName ?? "");
                            if (e.IncomingPeopleId == null) e.Error = "进货人链接失败";
                        });
                    }
                    // 链接 制单人
                    var makeSingleIdLabelList = pageItems.Where(x => x.MakeSingleFkDisplayName != null).Select(x => x.MakeSingleFkDisplayName).Distinct().ToList();
                    if (makeSingleIdLabelList.Any()) {
                        var makeSingleIdLinkMap = _incomingordersRep.Context.Queryable<UserInfo>().Where(u => makeSingleIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.MakeSingleId = makeSingleIdLinkMap.GetValueOrDefault(e.MakeSingleFkDisplayName ?? "");
                            if (e.MakeSingleId == null) e.Error = "制单人链接失败";
                        });
                    }
                    // 链接 所在部门
                    var depIdLabelList = pageItems.Where(x => x.DepFkDisplayName != null).Select(x => x.DepFkDisplayName).Distinct().ToList();
                    if (depIdLabelList.Any()) {
                        var depIdLinkMap = _incomingordersRep.Context.Queryable<department>().Where(u => depIdLabelList.Contains($"{u.DepartmentName}")).ToList().ToDictionary(u => $"{u.DepartmentName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DepId = depIdLinkMap.GetValueOrDefault(e.DepFkDisplayName ?? "");
                            if (e.DepId == null) e.Error = "所在部门链接失败";
                        });
                    }
                    // 链接 操作人
                    var operatorLabelList = pageItems.Where(x => x.OperatorFkDisplayName != null).Select(x => x.OperatorFkDisplayName).Distinct().ToList();
                    if (operatorLabelList.Any()) {
                        var operatorLinkMap = _incomingordersRep.Context.Queryable<UserInfo>().Where(u => operatorLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Operator = operatorLinkMap.GetValueOrDefault(e.OperatorFkDisplayName ?? "");
                            if (e.Operator == null) e.Error = "操作人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Incomingorders>>();
                    
                    var storageable = _incomingordersRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.IncomingNumber?.Length > 32, "进货单号长度不能超过32个字符")
                        .SplitError(it => it.Item.OrdersStatus?.Length > 32, "单据状态长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.ContactManaer?.Length > 32, "联系方式长度不能超过32个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 32, "进货货品长度不能超过32个字符")
                        .SplitError(it => it.Item.IncomingDesc?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.OrganizationalStructureId?.Length > 32, "进货明细长度不能超过32个字符")
                        .SplitError(it => it.Item.StorageDesc?.Length > 32, "上传附件长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
